package src.com.neusoft.nep.controller;

import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.StringConverter;
import src.com.neusoft.nep.common.AQI;
import src.com.neusoft.nep.common.AdAlertUtils;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;

import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

public class ProvinceAQIDateController {
    @FXML
    private TableView<Map<String, String>> tableView;
    @FXML
    private TableColumn<Map<String, String>, String> colNumber, colProvince, colCity, colSO2, colCO, colPM, colAQI, colDate;
    @FXML
    private DatePicker datePicker;

    private Map<String, ProvidedData> dataMap; // 存储读取的数据
    private List<Map<String, String>> allTableData = new ArrayList<>(); // 所有表格数据
    private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private final AQI aqiAnalyzer = new AQI();

    public void initialize() {
        // 初始化表格列
        setupTableColumns();

        // 加载数据
        loadData();

        // 设置日期选择器格式
        setupDatePicker();

        // 默认显示今天的数据
        datePicker.setValue(LocalDate.now());
        queryByDate(LocalDate.now());
    }

    private void setupTableColumns() {
        colNumber.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("number")));
        colProvince.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("province")));
        colCity.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("city")));
        colSO2.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("so2Level")));
        colCO.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("coLevel")));
        colPM.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("pmLevel")));
        colAQI.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("aqiLevel")));
        colDate.setCellValueFactory(cellData ->
                new javafx.beans.property.SimpleStringProperty(cellData.getValue().get("date")));

        // 设置列标题
        colSO2.setText("SO2等级");
        colCO.setText("CO等级");
        colPM.setText("PM等级");
        colAQI.setText("AQI等级");
    }

    private void loadData() {
        try {
            // 从文件读取数据
            dataMap = FileUtils.readMapObject("AdminData.txt");

            if (dataMap == null || dataMap.isEmpty()) {
                throw new RuntimeException("数据文件为空或读取失败");
            }

            // 转换数据格式
            convertDataMapToTableData();

        } catch (Exception e) {
            e.printStackTrace();
            AdAlertUtils.showDialog("错误", "加载数据失败: " + e.getMessage());
        }
    }

    private void setupDatePicker() {
        // 设置日期选择器格式
        datePicker.setConverter(new StringConverter<LocalDate>() {
            @Override
            public String toString(LocalDate date) {
                if (date != null) {
                    return dateFormatter.format(date);
                }
                return "";
            }

            @Override
            public LocalDate fromString(String string) {
                if (string != null && !string.isEmpty()) {
                    return LocalDate.parse(string, dateFormatter);
                }
                return null;
            }
        });

        // 监听日期选择器变化
        datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                queryByDate(newValue);
            }
        });
    }

    private void convertDataMapToTableData() {
        allTableData.clear();

        int counter = 1;
        for (Map.Entry<String, ProvidedData> entry : dataMap.entrySet()) {
            String key = entry.getKey();
            ProvidedData data = entry.getValue();

            // 获取省市信息（优先使用对象属性，否则从键解析）
            String province = getProvince(data, key);
            String city = getCity(data, key);

            // 获取污染物浓度
            double so2 = Double.parseDouble(data.getSo2());
            double co = Double.parseDouble(data.getCo());
            double pm = Double.parseDouble(data.getPm());
            LocalDate date = LocalDate.parse(data.getDate());

            // 计算等级
            int so2Level = aqiAnalyzer.getLevel(so2, "so2");
            int coLevel = aqiAnalyzer.getLevel(co, "co");
            int pmLevel = aqiAnalyzer.getLevel(pm, "pm");
            int aqiLevel = Math.max(Math.max(so2Level, coLevel), pmLevel);

            // 创建表格行数据
            Map<String, String> row = new HashMap<>();
            row.put("number", String.valueOf(counter++));
            row.put("province", province);
            row.put("city", city);
            row.put("so2Level", String.valueOf(so2Level));
            row.put("coLevel", String.valueOf(coLevel));
            row.put("pmLevel", String.valueOf(pmLevel));
            row.put("aqiLevel", String.valueOf(aqiLevel));
            row.put("date", date.format(dateFormatter));

            allTableData.add(row);
        }
    }

    private String getProvince(ProvidedData data, String key) {
        String province = data.getProvince();
        if (province != null && !province.isEmpty()) {
            return province;
        }

        // 尝试从键解析
        String[] parts = key.split("-");
        return parts.length > 0 ? parts[0] : "未知省份";
    }

    private String getCity(ProvidedData data, String key) {
        String city = data.getCity();
        if (city != null && !city.isEmpty()) {
            return city;
        }

        // 尝试从键解析
        String[] parts = key.split("-");
        return parts.length > 1 ? parts[1] : "未知城市";
    }

    private void queryByDate(LocalDate date) {
        if (date == null) {
            tableView.getItems().clear();
            return;
        }

        // 格式化日期
        String targetDate = date.format(dateFormatter);

        // 筛选指定日期的数据（不做任何聚合，保留所有记录）
        List<Map<String, String>> filteredData = allTableData.stream()
                .filter(row -> targetDate.equals(row.get("date")))
                .collect(Collectors.toList());

        // 更新表格数据
        tableView.getItems().setAll(filteredData);

        if (filteredData.isEmpty()) {
            AdAlertUtils.showDialog("查询结果", "所选日期没有数据记录");
        }
    }
}